<template>
  <div class="px-5 py-12 sm:py-16">
    <GoogleAuthLogin></GoogleAuthLogin>
    <div class="form-container">
      <div class="flex items-center justify-center">
        <common-link path="/"
          class="go-home">
          <span class="sr-only">Toolify</span>
          <img class="h-8 w-auto sm:h-11"
            src="@/static/images/logo.png"
            alt="Toolify logo" />
        </common-link>
      </div>
      <div class="mt-11">
        <h1 class="text-gray-1000 font-semibold title break-words">{{$t('signInToYourMccount')}}</h1>
        <p class="text-gray-1000 text-base mt-5 desc break-words">{{$t('signInWith')}}</p>

        <el-button class="w-full h-11 mt-8 py-0 to-getLoginCode"
          :class="{'googleLoading':googleLoading}"
          @click="toGetLoginCode"
          :loading="googleLoading">
          <div class="flex items-center justify-center">
            <svg-icon iconName='google_default'
              :class-name="googleLoading ? 'loading' : ''"
              class="w-6 h-6"></svg-icon>
            <span class="text-gray-1000 text-base ml-6">{{$t('contiuneWithGoogle')}}</span>
          </div>
        </el-button>
        <div class="px-10">
          <el-divider class="my-7 whitespace-nowrap">{{$t('orContinueWith')}}</el-divider>
        </div>
        <div class="form">
          <el-form :model="form"
            :rules="rules"
            ref="form">
            <el-form-item :label="$t('email')"
              prop="email">
              <el-input v-model="form.email"
                :placeholder="$t('pleaseEnterYourEmailAddress')"
                @keyup.enter.native="submitForm"></el-input>
            </el-form-item>
            <el-form-item :label="$t('password')"
              prop="password">
              <el-input type="password"
                v-model="form.password"
                :placeholder="$t('pleaseEnterYourPassword')"
                autocomplete="off"
                show-password
                @keyup.enter.native="submitForm"></el-input>
            </el-form-item>
            <div class="flex items-center justify-between">
              <el-checkbox v-model="isSaveMsg">{{$t('rememberMe')}}</el-checkbox>
              <common-link path="/forgetPassword"
                class="text-purple-1300 text-base hover:text-purple-1200 go-forget-password">
                {{$t('forgotYourPassword')}}
              </common-link>
            </div>
            <el-form-item class="mt-6">
              <el-button type="primary"
                :loading="loading"
                @click.native.prevent="submitForm"
                class="w-full h-11 to-signIn">{{$t('signIn')}}</el-button>
            </el-form-item>
          </el-form>
          <div class="mt-7 text-center">
            <span class="text-gray-1500 text-sm">{{$t('dontNotHaveAnAccountYet')}}</span>

            <common-link :path="`/register${$route.query.from?'?from='+$route.query.from:''}`"
              class="text-sm font-medium text-purple-1300 hover:text-purple-1200 underline ml-2 go-register">
              <span>{{$t('signUp')}}</span>
            </common-link>
          </div>
        </div>
        <div class="flex justify-center mt-6 language">
          <common-language :has-border="false"></common-language>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isEmail } from '@/plugins/validate'
import { mapState, mapMutations } from 'vuex'
import md5 from 'js-md5'
export default {
  name: 'LoginPage',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, store }) {
    let pageDesc = app.$cookies.get('pageDesc')
    try {
      let [langRes] = await Promise.all([await $axiosApi.getLanguagesMul()])

      let description
      let curLocale = store.state.locale
      if (
        langRes.code === 200 &&
        langRes.data &&
        langRes.data.languages &&
        langRes.data.languages.description &&
        langRes.data.languages.description.length > 0 &&
        langRes.data.languages.description[0].content &&
        (langRes.data.languages.description[0].content[curLocale] ||
          langRes.data.languages.description[0].content.default)
      ) {
        if (langRes.data.languages.description[0].content[curLocale]) {
          description = langRes.data.languages.description[0].content[curLocale]
        } else {
          description = langRes.data.languages.description[0].content.default
        }

        app.$cookies.set('pageDesc', description, {
          maxAge: 60 * 60 * 24 * 7,
          path: '/',
        })
      } else if (pageDesc) {
        description = pageDesc
      }

      return {
        description,
      }
    } catch (err) {
      console.log(err)
    }
  },
  data() {
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$i18n.t('pleaseEnterYourEmailAddress')))
      } else if (!isEmail(value)) {
        callback(new Error(this.$i18n.t('pleaseInputAValidEmail')))
      } else {
        callback()
      }
    }
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      form: {
        email: '',
        password: '',
      },
      rules: {
        email: [
          {
            required: true,
            message: this.$i18n.t('pleaseEnterYourEmailAddress'),
            trigger: 'change',
          },
          {
            validator: validateEmail,
            trigger: 'change',
          },
        ],
        password: [
          {
            required: true,
            message: this.$i18n.t('pleaseEnterYourPassword'),
            trigger: 'change',
          },
          {
            min: 6,
            message: this.$i18n.t('correctPassword'),
            trigger: 'change',
          },
        ],
      },
      loading: false,
      isSaveMsg: false,

      googleLoading: false,
      description: null,
    }
  },
  computed: {
    ...mapState({
      languagesOptions: (state) => state.languagesOptions,
      toolify_isLogin: (state) => state.toolify_isLogin,
      locale: (state) => state.locale,
    }),
  },
  watch: {
    locale(val) {
      this.$i18n.locale = val
    },
    form: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.isSaveMsg) {
          this.$cookies.set('accountForm', JSON.stringify(val), {
            maxAge: 60 * 60 * 24 * 30,
            path: '/',
          })
        }
      },
    },
    isSaveMsg(val) {
      this.$cookies.set('isSaveMsg', val)
      if (val) {
        this.$cookies.remove('accountForm')
        this.$cookies.set('accountForm', JSON.stringify(this.form), {
          maxAge: 60 * 60 * 24 * 30,
          path: '/',
        })
      }
    },
  },
  filters: {
    fLocale: function (val, languagesOptions) {
      let res = languagesOptions.find((item) => {
        return item.value === val
      })
      if (res) {
        return res.label
      } else {
        return '-'
      }
    },
  },
  created() {
    if (this.$cookies.get('toolify_isLogin')) {
      this.$router.replace('/')
    }
  },
  mounted() {
    if (this.$route.query.code) {
      this.toGoogleAuthLogin()
    }
    if (this.$cookies.get('isSaveMsg')) {
      this.isSaveMsg = true
      if (this.$cookies.get('accountForm')) {
        const accountForm = this.$cookies.get('accountForm')
        if (accountForm) {
          this.form = { ...accountForm }
        }
      }
    }
  },
  methods: {
    ...mapMutations(['SET_ISLOGIN', 'SET_LANG', 'SET_USERINFO']),
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            const res = await this.$axiosApi.login({
              email: this.form.email,
              password: md5(this.form.password),
            })
            this.loading = false
            if (res && res.code === 200) {
              if (res.data && res.data.user) {
                this.SET_USERINFO(res.data.user)
              }
              if (res.data && res.data.user && res.data.user.language) {
                this.SET_LANG(res.data.user.language)
              }
              this.SET_ISLOGIN(true)
              //this.$message.success(this.$i18n.t('signInSuccess'))

              if (this.$route.query.from) {
                this.$router.push({
                  name: this.$route.query.from,
                  params: { lang: this.locale },
                })
              } else {
                this.$router.push({
                  path: this.locale === 'en' ? '/' : `/${this.locale}`,
                })
              }
            } else {
              //this.$message.error(res.message)
            }
          } catch (error) {
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCommand(value) {
      this.$store.commit('SET_LANG', value)
    },
    async toGetLoginCode() {
      this.googleLoading = true
      try {
        const res = await this.$axiosApi.authGoogleAuthUrl({
          redirect_uri: `${window.location.origin}/login`,
        })

        this.googleLoading = false
        if (res && res.code === 200 && res.data.auth_url) {
          window.location.replace(res.data.auth_url)
        } else {
          //this.$message.error(res.message)
        }
      } catch (error) {
        this.googleLoading = false
      }
    },
    async toGoogleAuthLogin(content) {
      this.googleLoading = true
      try {
        let req = {}
        let query = {}

        if (this.$route.query.code) {
          req.code = this.$route.query.code

          if (this.$cookies.get('utm')) {
            req.source = this.$cookies.get('utm')
          } else {
            req.source = null
          }
          req.redirect_uri = `${window.location.origin}/login`
        } else if (content) {
          req = {
            credential: content.credential,
            source: this.$cookies.get('utm') || null,
          }
        }

        let redirect = this.$cookies.get('toolifyRedirect')
        if (redirect) {
          this.$router.replace({
            query: { from: redirect },
          })
        }

        if (this.$route.query && this.$route.query.redirect) {
          query.redirect = this.$route.query.redirect
        }

        const res = await this.$axiosApi.authGoogleLogin(req)
        this.googleLoading = false
        if (res && res.code === 200) {
          if (res.data && res.data.user) {
            this.SET_USERINFO(res.data.user)
          }
          this.SET_ISLOGIN(true)

          //this.$message.success(this.$i18n.t('signInSuccess'))

          if (this.$route.query.from) {
            this.$router.push({
              name: this.$route.query.from,
              params: { lang: this.locale },
            })
          } else {
            this.$router.push({
              path: this.locale === 'en' ? '/' : `/${this.locale}`,
            })
          }
        } else {
          //this.$message.error(res.message)
        }
      } catch (error) {
        this.googleLoading = false
        console.log(error)
      }
    },
  },
}
</script>
<style lang='scss' scoped>
.form-container {
  max-width: 435px;
  margin: 0 auto;

  .title {
    font-size: 28px;
  }

  ::v-deep .el-divider--horizontal {
    .el-divider__text {
      color: #666;
    }
  }
  ::v-deep .form {
    .el-form-item__label {
      font-weight: 600;
      line-height: 16px;
      margin-bottom: 12px;
    }
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-checkbox__inner {
      width: 18px;
      height: 18px;
      &::after {
        left: 5px;
        width: 4px;
        height: 9px;
      }
    }
    .el-checkbox__label {
      color: #666666;
    }
    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #7150e6;
    }
    .el-form-item__error {
      font-size: 14px;
    }
  }
}
::v-deep.googleLoading {
  &.is-loading {
    .el-icon-loading {
      display: none;
    }
  }
  & > span {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.loading {
  animation: rotation 1s linear infinite;
}
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
